/**
 * Created by chenweicheng on 19/6/18.
 */
/**
 * Created by chenweicheng on 15/7/17.
 */
import React, {PureComponent} from 'react'
import {View, Text, StyleSheet, Image, TouchableOpacity, NativeAppEventEmitter, Platform, Alert} from 'react-native'

import {NavigationActions} from 'react-navigation'
import {px2dpH, px2dpW} from '../config/px2dp'
import Camera from 'react-native-camera';
import theme from '../config/theme'
import ModalDialog from '../widget/ModalDialog'
import ModalListDialog from '../widget/ModalListDialog'
import ModalSliderDialog from '../widget/ModalSliderDialog'
import UtilManager from '../util/UtilManager'
import  MsgManager from "../manager/MsgManager"
import  TcpManager from "../manager/TcpManager"

import RNFS from 'react-native-fs';
import Spinner from 'react-native-loading-spinner-overlay'

export  default class ScanCodeResultScene extends PureComponent {
    static navigationOptions = ({navigation}) => ({


        headerTitle: navigation.state.params.type,


        headerRight: <View/>,
        headerStyle: theme.headerStyle,


    });


    constructor() {
        super();

        this.state = {
            reload: false
        }
        this.modalvisable = false
        this.modalslidervisable = false
        this.sliderValue = 1;

        this.listDialogvisable = false
        this.list = [{title: 'a', desc: 'a'}, {title: 'b', desc: 'a'}, {title: 'c', desc: 'a'}]


        this.visible = false
        this.itemSelected = 1;
        this.datainfo = {"start": "", "length": 0, rate: 0, groups: 0}

        this.startSn = ""


        this.getdatatip = ""

        this.currentWavIndex = 0;
        this.wavList = [];


    }

    reload() {
        this.setState({reload: !this.state.reload})
    }

    componentDidMount() {

        console.log("扫描结果", this.props.navigation.state.params.data, this.props.navigation.state.params.type)

    }


    componentWillMount() {

    }

    componentWillUnmount() {
        NativeAppEventEmitter.emit('aaa', 'aaa')
    }


    start(time) {
        console.log("start time", time)

        MsgManager.start(time).then((result) => {
            console.log("getdata", result.loopcount, result.msg)
            //  alert("启动成功")

            if (TcpManager.tcpReady) {
                TcpManager.send(result.loopcount, result.msg, (data) => {
                    console.log("start callback", data)
                    if (data.type == 4 && data.ret == 1) {
                        this.cancel()

                        this.timeout = setTimeout(() => {
                            alert("启动成功")
                        }, 300)

                    }

                }, false);
            } else {


            }

        }, (fail) => {
            console.log(fail)
            alert("启动失败，请重试")

        })
        // this.cancel()

    }

    cancel() {
        console.log("cancel")
        this.modalvisable = false
        this.listDialogvisable = false
        this.modalslidervisable = false
        this.reload()
    }

    show(sn) {
        this.modalvisable = true
        this.startSn = sn

        this.reload()
    }

    showList() {
        this.listDialogvisable = true
        this.reload()
    }

    showSlider() {
        this.modalslidervisable = true
        this.reload()
    }

    tcpConnect(ip, port) {
        let client = TcpManager.clientConnect(ip, port)

        TcpManager.client.on('data', this.ondata.bind(this));

    }

    ondata(zz) {

        console.log("ScanCodeResultScene  Received:", zz)
    }

    writeFile(data, name) {
        //  create a path you want to write to
        const path = theme.getPath(name)//(Platform.OS === 'ios' ? RNFS.MainBundlePath : RNFS.ExternalStorageDirectoryPath ) + '/' + name + '.txt';

        //write the file
        return new Promise((fulfill, reject) => {
            RNFS.writeFile(path, data, 'utf8')
                .then((success) => {
                    console.log('writeFile path', path);
                    fulfill(path)
                })
                .catch((err) => {
                    console.log(err.message);
                    reject(err.message)
                });
        })

    }

    getData1() {
        MsgManager.getData(this.itemSelected).then((result) => {
            console.log("getdata", result.loopcount, result.msg)

            if (TcpManager.tcpReady) {

                this.visible = true
                this.cancel()
                this.getdatatip = "正在获取鼻鼾数据"
                this.reload()


                TcpManager.send(result.loopcount, result.msg, (data) => {
                    console.log("getdata callback", data)


                    //todo 保存频率和时间长度

                    //  this.datainfo = {"start": "", "length": 0, rate: 0, groups: 0}
                    let m = this.datainfo.start + "&" + this.datainfo.length + "&" + this.datainfo.rate + "&" + this.datainfo.groups

                    theme.datatrue = false
                    theme.releaseData()
                    this.writeFile(m, "snapinfo.txt").then((path) => {
                        console.log("path", path)


                    }, (error) => {
                        console.log("error", error)
                    })
                    this.writeFile(data, "snapdata.txt").then((path) => {
                        console.log("path", path)
                        this.getData2()
                    }, (error) => {
                        console.log("error", error)
                    })

                }, true);


            } else {

            }


        }, (fail) => {
            alert(fail)
        })
    }

    getData2() {
        MsgManager.getDataEnv(this.itemSelected).then((result) => {
            console.log("get  env data", result.loopcount, result.msg)

            if (TcpManager.tcpReady) {


                this.visible = true
                this.cancel()
                this.getdatatip = "正在获取环境数据"
                this.reload()


                TcpManager.send(result.loopcount, result.msg, (data) => {
                    console.log("get env data callback", data)

                    this.writeFile(data, "snapenvdata.txt").then((path) => {
                        console.log("data env path", path)

                       // this.getWavList()

                        this.visible = false

                        this.reload()
                        setTimeout(() => {
                            alert("获取完毕数据")
                        }, 500)

                    }, (error) => {
                        console.log("error", error)
                    })
                }, true);

            } else {

            }


        }, (fail) => {
            alert(fail)
        })
    }


    getWav(index) {
        MsgManager.getWav(this.wavList[index].index).then((result) => {
            console.log("get wav ", result.loopcount, result.msg)

            TcpManager.send(result.loopcount, result.msg, (datawav) => {
                console.log("get wav  callback", datawav)


                let data2 = datawav.substring(46, datawav.length)
                console.log("data2", data2)


                console.log("this.wavList[index].name", this.wavList[index].name)

                console.log("this.wavList[index].name.toLowerCase()", this.wavList[index].name.toLowerCase())

                UtilManager.createFileWithByte(data2, theme.getPath(this.wavList[index].name.toLowerCase() + '.wav')).then((suc) => {
                    console.log("save wav suc", suc)
                }, (fail) => {
                    console.log("error", fail)
                })

                // this.writeFile(datawav, "snapwav").then((path) => {
                //     console.log("snapwavpath", path)
                //
                //
                // }, (error) => {
                //     console.log("error", error)
                // })


                if (index == this.wavList.length - 1) {
                    this.visible = false
                    this.currentWavIndex = 0;
                    this.wavList = []

                    this.reload()
                    setTimeout(() => {
                        alert("获取完毕录音数据")
                    }, 500)
                } else {
                    this.currentWavIndex = this.currentWavIndex + 1;
                    this.getWav(this.currentWavIndex)
                }

            }, true);


        }, (fail) => {
            alert(fail)
        })
    }


    getWavList() {
        MsgManager.getWavList(this.itemSelected).then((result) => {
            console.log("get wav list", result.loopcount, result.msg)

            if (TcpManager.tcpReady) {


                this.visible = true
                this.cancel()
                this.getdatatip = "正在获取音频列表"
                this.reload()


                TcpManager.send(result.loopcount, result.msg, (data) => {
                    console.log("get wav list callback", data)
                    this.wavList = data.audioList.audio;

                    let nameList = ""
                    for (let i = 0; i < this.wavList.length; i++) {
                        if (nameList == "") {
                            nameList = this.wavList[i].name.toLowerCase()
                        } else {
                            nameList = nameList + "&" + this.wavList[i].name.toLowerCase()
                        }
                    }
                    this.writeFile(nameList, "snapwavlist.txt").then((path) => {
                        console.log("path", path)
                    }, (error) => {
                        console.log("error", error)
                    })

                    this.currentWavIndex = 0;

                    if (this.wavList.length > 0) {
                        this.getWav(this.currentWavIndex)
                    } else {
                        this.visible = false

                        this.reload()
                        setTimeout(() => {
                            alert("获取完毕数据")
                        }, 500)
                    }

                    // { loopCount: 3,
                    //     type: 8,
                    //     audioList: { length: 1, audio: [ { name: '5b471e4c' } ] } }
                }, false);

            } else {

            }


        }, (fail) => {
            alert(fail)
        })
    }


    getData() {
        this.getData1()

    }

    getdatalist() {
        MsgManager.getDataList().then((result) => {
            console.log(result.loopcount, result.msg)

            if (TcpManager.tcpReady) {
                console.log("tcpReady true")
                TcpManager.send(result.loopcount, result.msg, (data) => {
                    console.log("getdatalist callback", data)

                    this.visible = false
                    this.list = data.dataList.data

                    this.datainfo = {
                        "start": data.dataList.data[0].startTime,
                        "length": data.dataList.data[0].timeLength,
                        rate: data.dataList.data[0].rate,
                        groups: data.dataList.data[0].dataGroups
                    }

                    console.log("current data info", this.datainfo)
                    this.showList()

                }, false);
            } else {
                console.log("tcpReady false")

            }

        }, (fail) => {
            alert(fail)
        })

    }

    afterTcpReady(sn) {

        switch (this.props.navigation.state.params.type) {
            case '快速检测':
                this.showSlider()

                break
            case '启动设备':
                this.show(sn)
                break
            case '查看数据':


                this.visible = true
                this.reload()
                this.getdatalist()

                break
        }

    }


    // getWav(index) {
    //     MsgManager.getWav(index).then((result) => {
    //         console.log("get wav ", result.loopcount, result.msg)
    //
    //
    //     }, (fail) => {
    //         alert(fail)
    //     })
    // }

    startListen() {
        console.log("startListen")
        UtilManager.receiveSpecLenByte(9331, 60000, 0).then((callback) => {
            //'#3:192.168.001.135&mysncode'
            //判断sn是否匹配

            //匹配进行tcp连接
            //this.tcpConnect()

            //如果是查看数据，需要发现查询命令
            console.log("receiveSpecLenByte suc", callback)
            let split1 = callback.split("&")
            let sn = split1[1]
            let ip = split1[0].substring(3, split1[0].length)

            console.log("sn", sn)
            console.log("ip", ip)


            //   let client = TcpManager.clientConnect(ip, 9123)
            if (this.props.navigation.state.params.data == sn) {

                // if (TcpManager.isSnReady(sn)) {
                //     this.afterTcpReady(sn)
                // } else {
                TcpManager.tcpReady = false
                TcpManager.clientConnect(ip, 9123, sn).then((client) => {
                    this.client = client
                    if (TcpManager.tcpReady) {
                        console.log("tcpReady true")

                        this.afterTcpReady(sn)
                    } else {
                        console.log("tcpReady false")
                        alert("未成功连接设备，请重新让设备广播并点击监听按钮")

                    }
                }, (error) => {
                    console.log("client tcp error", error)
                    alert("未成功连接设备，请重新让设备广播并点击监听按钮")
                })
                // }


                //连接成功后，弹出不同的窗
            } else {
                // this.startListen()
                alert("未搜索到设备，请重新让设备广播并点击监听按钮")
            }


        }, (error) => {
            console.log("fail", error)
        })
    }

    itemClick(index) {
        console.log("itemClick", index)
        this.itemSelected = index + 1
        this.datainfo = {
            "start": this.list[index].startTime,
            "length": this.list [index].timeLength,
            rate: this.list [index].rate,
            groups: this.list [index].dataGroups
        }
        console.log("current data info", this.datainfo)


    }

    onValueChange(val) {
        console.log("onValueChange", val)
    }

    onSlidingComplete(val) {
        this.sliderValue = val
        this.reload()
        console.log("onSlidingComplete", val)
    }

    render() {

        return (
            <View style={styles.container}>

                <Text>让设备进入广播状态，并点击下方监听按钮</Text>
                <TouchableOpacity onPress={this.startListen.bind(this)}
                                  style={styles.btnbg}>
                    <Text style={styles.btntext}>开始监听</Text>
                </TouchableOpacity>


                {/*<TouchableOpacity onPress={()=> {this.getWavList()}}*/}
                {/*style={styles.btnbg}>*/}
                {/*<Text style={styles.btntext}>获取音频列表</Text>*/}
                {/*</TouchableOpacity>*/}
                {/*<TouchableOpacity onPress={()=> {this.getWav(1)}}*/}
                {/*style={styles.btnbg}>*/}
                {/*<Text style={styles.btntext}>获取音频</Text>*/}
                {/*</TouchableOpacity>*/}
                {/*<TouchableOpacity onPress={()=> {this.getdatalist()}}*/}
                {/*style={styles.btnbg}>*/}
                {/*<Text style={styles.btntext}>测试查询数据列表</Text>*/}
                {/*</TouchableOpacity>*/}
                {/*<TouchableOpacity onPress={()=> {this.getData(1)}}*/}
                {/*style={styles.btnbg}>*/}
                {/*<Text style={styles.btntext}>测试查询数据列表</Text>*/}
                {/*</TouchableOpacity>*/}

                {/*<Text style={{fontSize:20}} onPress={this.show.bind(this)}>基本</Text>*/}
                {/*<Text style={{fontSize:20}} onPress={this.showSlider.bind(this)}>slider</Text>*/}
                {/*<Text style={{fontSize:20}} onPress={this.showList.bind(this)}>列表</Text>*/}
                <ModalDialog
                    _dialogVisible={this.modalvisable}
                    _dialogLeftBtnAction={()=> {this.start(11)}}
                    _dialogRightBtnAction={()=> {this.cancel()}}
                    _dialogContent={this.startSn}
                    _dialogLeftBtnTitle={'启动'}
                    _dialogRightBtnTitle={'取消'}
                />


                {/*<ModalDialog*/}
                {/*_dialogVisible={this.getdatavisible}*/}
                {/*_dialogLeftBtnAction={()=> {this.start(11)}}*/}
                {/*_dialogRightBtnAction={()=> {this.cancel()}}*/}
                {/*_dialogContent={this.getdatatip}*/}
                {/*_dialogLeftBtnTitle={'确定'}*/}
                {/*_dialogRightBtnTitle={'取消'}*/}
                {/*/>*/}

                <ModalListDialog
                    _dialogVisible={this.listDialogvisable}
                    _dialogLeftBtnAction={()=> {this.getData()}}
                    _dialogRightBtnAction={()=> {this.cancel()}}
                    _dialogLeftBtnTitle={'确定'}
                    _dialogRightBtnTitle={'取消'}
                    itemClick={this.itemClick.bind(this)}
                    list={this.list}
                />
                < ModalSliderDialog

                    _dialogVisible={this.modalslidervisable}
                    _dialogLeftBtnAction={()=> {this.start(this.sliderValue)}}
                    _dialogRightBtnAction={()=> {this.cancel()}}
                    _dialogContent={"需要更新固件"}
                    _dialogLeftBtnTitle={'启动'}
                    _dialogRightBtnTitle={'取消'}
                    value={this.sliderValue}
                    title={'检测sn号:'+this.props.navigation.state.params.data}
                    onValueChange={this.onValueChange.bind(this)}
                    onSlidingComplete={this.onSlidingComplete.bind(this)}/>
                <Spinner visible={this.visible} textContent={this.getdatatip} cancelable={true}/>
            </View>)
    }
}


const
    styles = StyleSheet.create({
        container: {
            flex: 1,
            backgroundColor: '#ffffff',
            alignItems: 'center'

        },
        btnbg: {
            width: px2dpW(100),
            height: px2dpH(40),
            alignItems: 'center',
            justifyContent: 'center',
            backgroundColor: 'rgb(68,154,208)',
            borderRadius: px2dpW(4)
        },
        btntext: {
            color: '#ffffff',
            fontSize: 13
        },

    });
